package com.lml.yunpicturesbackend.controller;

import com.lml.yunpicturesbackend.annotation.AuthCheck;
import com.lml.yunpicturesbackend.common.BaseResponse;
import com.lml.yunpicturesbackend.common.ResultUtils;
import com.lml.yunpicturesbackend.constant.UserConstant;
import com.lml.yunpicturesbackend.exception.BusinessException;
import com.lml.yunpicturesbackend.exception.ErrorCode;
import com.lml.yunpicturesbackend.manager.CosManager;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * @author 梦龙
 * @date 2025/5/5 上午10:27
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private CosManager cosManager;

    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test/upload")
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile multipartFile) {
        // 文件目录
        String filename = multipartFile.getOriginalFilename();
        String filepath = String.format("/test/%S", filename);
        File file = null;
        try {
            file = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filepath, file);
            return ResultUtils.success(filepath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "上传失败");
        } finally {
            boolean delete = file.delete();
            if (!delete) {
                log.error("file delete error, filepath = {}" + filepath);
            }
        }
    }

    /**
     * 测试文件下载
     * @param filepath
     * @param response
     * @throws Exception
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @GetMapping("/test/download")
    public void testDownload(String filepath, HttpServletResponse response) throws Exception {
        COSObjectInputStream cosObjectInputStream = null;
        try {
            // 获得COSObject对象
            COSObject cosObject = cosManager.getObject(filepath);
            // 得到对象存储的对象的输入流
            cosObjectInputStream = cosObject.getObjectContent();
            byte[] bytes = IOUtils.toByteArray(cosObjectInputStream);
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filepath);
            // 写入响应
            response.getOutputStream().write(bytes);
            // 刷新缓冲区
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("download error, filepath = "+ filepath,e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"下载失败");
        } finally {
            // 释放流
            if (cosObjectInputStream != null){
                cosObjectInputStream.close();
            }
        }

    }
}
